/**
 * 
 */
package com.jzcodecheck.ui.template.function;

import java.util.List;

import com.autoscript.ui.helper.TypeConversionHelper;
import com.jzcodecheck.ui.helper.UIPropertyHelper;

import freemarker.template.TemplateMethodModel;
import freemarker.template.TemplateModelException;

/**
 * 获取随机数
 * @author 龙色波
 * @日期 2017-01-11
 */
public class RandomNumber implements TemplateMethodModel {

	@Override
	public Object exec(List args) throws TemplateModelException {
		// 格式:RandomNumber(随机数位数,进制)
		//进制 ：10进制或16进制
		if(args.size()!=2){
			throw new TemplateModelException(UIPropertyHelper.getString("exception.func_para_number_not_match","RandomNumber",args.size(),"2"));
		}	
		int num=0;
		try {
		    num = TypeConversionHelper.StringToInt((String) args.get(0));
		} catch (Exception e) {
			e.printStackTrace();
			throw new TemplateModelException(UIPropertyHelper.getString("exception.invalidateFuncParamType","RandomNumber",1,"数字","字符串"));
		}
		int hex = 10;
		try {
		    hex = TypeConversionHelper.StringToInt((String) args.get(1));		    
		} catch (Exception e) {
			e.printStackTrace();
			throw new TemplateModelException(UIPropertyHelper.getString("exception.invalidateFuncParamType","RandomNumber",2,"数字","字符串"));
		}
		if(hex!=10 && hex!=16){
			throw new TemplateModelException(UIPropertyHelper.getString("exception.invalidateFuncParamValue","RandomNumber",2,"10或16",hex));
		}
		return getRandomNumberByNum(num,hex);
	}
	
	private String getRandomNumberByNum(int num,int hex ) {  
        StringBuffer sb = new StringBuffer();
        int max =hex==10?10:16;
        for (int i = 0; i < num; i++) {  
            long randomNum = Math.round(Math.floor(doRandomNum(max,0)));
            if(hex==10){
            	sb.append(randomNum);
            }else{
            	sb.append(String.format("%X", randomNum));
            }
        }  
        return sb.toString();  
    }  
	/**
     * 生成指定范围随机数
     * 
     */ 
    public long doRandomNum(long max ,long min){
    
    	return Math.round(Math.random()*(max-min))+min;
    	
    }
}
